import { Injectable } from '@angular/core'
import { NzModalService } from 'ng-zorro-antd'
import { PageService } from '@shared/services/page.service'
import { I18NService } from '@core'
import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate, Router } from '@angular/router'
import { SettingsService } from '@delon/theme'
import { User } from '@shared/interfaces/user'
import { EUserType } from '@shared/enums'

enum EBizUrl {
  Acquirer = '/biz/acquirers/list',
  Group = '/biz/groups/list',
  Merchant = '/biz/merchants/list',
  Store = '/biz/stores/list',
  Terminal = '/biz/terminals/list',
}

@Injectable({
  providedIn: 'root'
})
export class ListRouterGuardClass implements CanActivate {
  user: User

  constructor(
    private router: Router,
    private settings: SettingsService,
  ) {}

  canActivate(
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
  ): boolean {
    try {
      return this.check(currentState)
    } catch (e) {
      return true
    }
  }

  check(currentState: RouterStateSnapshot): boolean {
    if (this.settings) {
      this.user = this.settings.user as User
      const { userType, insCode, agentCode, intMerCode, intStoreCode } = this.user
      const url = currentState.url
      switch (userType) {
        case EUserType.Institution: {
          if (url === EBizUrl.Acquirer) {
            this.router.navigateByUrl(`/biz/acquirers/${insCode}`)
            return false
          }
          return true
        }

        case EUserType.Agent: {
          if (url === EBizUrl.Group) {
            this.router.navigateByUrl(`/biz/groups/${agentCode}`)
            return false
          }
          return true
        }

        case EUserType.Merchant: {
          if (url === EBizUrl.Merchant) {
            this.router.navigateByUrl(`/biz/merchants/${intMerCode}`)
            return false
          }
          return true
        }

        case EUserType.Store: {
          if (url === EBizUrl.Store) {
            this.router.navigateByUrl(`/biz/stores/${intStoreCode}`)
            return false
          }
          return true
        }

        default: return true
      }
    }
  }
}
